package com.xgq.drink.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xgq.drink.entity.Orders;
import com.xgq.drink.entity.ProductReview;
import com.xgq.drink.entity.R;
import com.xgq.drink.mapper.OrderMapper;
import com.xgq.drink.service.IProductReviewService;
import com.xgq.drink.utils.RUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 商品评价表 前端控制器
 * </p>
 *
 * @author xgq
 * @since 2025-03-06
 */
@RestController
@RequestMapping("/review")
@Tag(name = "商品评价模块", description = "商品评价相关接口")
public class ProductReviewController {

    @Autowired
    private IProductReviewService reviewService;
    @Autowired
    private OrderMapper orderMapper;

    @PostMapping("/add")
    @Operation(summary = "添加商品评价", description = "用户添加商品评价，支持追评模式")
    public R addReview(@RequestBody ProductReview review, HttpServletRequest request) {
        try {
            reviewService.addReview(review);
            Orders order = orderMapper.selectById(review.getOrderId());
            order.setStatus(8);
            orderMapper.updateById(order);
            return RUtils.success("评价添加成功");
        } catch (Exception e) {
            return RUtils.fail("评价添加失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除商品评价", description = "逻辑删除商品评价")
    public R deleteReview(@RequestParam Long reviewId) {
        try {
            reviewService.deleteReview(reviewId);
            return RUtils.success("评价删除成功");
        } catch (Exception e) {
            return RUtils.fail("评价删除失败: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    @Operation(summary = "查询商品评价", description = "根据商品ID查询商品评价")
    public R getReviewsByProductId(@RequestParam Long productId) {
        try {
            QueryWrapper<ProductReview> queryWrapper = reviewService.getReviewsByProductId(productId);
            List<ProductReview> reviews = reviewService.list(queryWrapper);
            return RUtils.success("查询成功", reviews);
        } catch (Exception e) {
            return RUtils.fail("查询失败: " + e.getMessage());
        }
    }
}
